<template>
  <div class="vip-label">
    <div class="row mb-1">
      <div class="col">
        <el-button @click="start" type="primary">查询</el-button>
        <el-button @click="dialogVisible = true" type="primary">添加</el-button>
      </div>
    </div>
    <el-table
      class="margin-top20"
      :data="tableData"
      height="73vh"
      style="width: 100%"
      @sort-change="sortchange"
    >
      <el-table-column prop="ID" label="ID"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <!-- <el-table-column prop="info" label="难度"></el-table-column> -->
      <el-table-column
        prop="createdAt"
        sortable="custom"
        :formatter="({ createdAt }) => formatter(createdAt)"
        label="创建时间"
      >
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button type="success" @click="addQuestion(row)" size="default"
            >题目</el-button
          >
          <el-button type="primary" @click="update(row)" size="default"
            >修改</el-button
          >
          <el-button
            v-if="!tenant_id"
            type="danger"
            @click="del(row?.ID)"
            size="default"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pager"
      @current-change="handleCurrentChange"
      :page-size="Number(limit)"
      :page-sizes="pageSizes"
      @size-change="handleSizeChange"
      layout="total, sizes ,prev, pager, next"
      :total="totalCount"
    >
    </el-pagination>
    <!-- 添加 -->
    <el-dialog
      width="500px"
      title=""
      v-model="dialogVisible"
      :draggable="true"
      @closed="resetFrom"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ fromData.ID ? "修改" : "添加" }}{{ LabelType.VIP }}
        </span>
      </template>
      <el-form
        ref="formRef"
        :model="fromData"
        label-width="auto"
        size="default"
      >
        <el-form-item
          label="精选题库标签"
          prop="name"
          :rules="[{ required: true, message: '请输入精选题库标签' }]"
        >
          <el-input
            v-model.trim="fromData.name"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item> </el-form-item>
        <div class="text-right">
          <el-button type="primary" @click="submit(formRef)">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 关联题库 -->
    <el-drawer
      class="my-el-drawer"
      size="75%"
      append-to="#app"
      v-model="showVipLabelQuestionDrawer"
      title="关联题目"
      @close="closeDrawer"
    >
      <template #header="{ close, titleId, titleClass }">
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          <span :id="titleId" :class="titleClass"
            >{{ selectedLabel?.name }}-题目列表</span
          >
        </span>
      </template>
      <el-row :gutter="40">
        <el-col :span="12">
          <VipQuestionSelect
            v-bind="{ vipLabel: selectedLabel }"
            @add-question="onAddQuestion"
          />
        </el-col>
        <el-col :span="12">
          <LabelQuestion
            v-bind="{ vipLabel: selectedLabel }"
            @set-refresh="setRefreshLabelQuestion"
          />
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { inject, onMounted, ref } from "vue";
import {
  asynccreateorupdatelabel,
  asyncdellabel,
  asyncselectlabel,
} from "../../../api/index";
import { toLocaleDateString } from "../../../util/time";

import { useStore } from "vuex";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import LabelQuestion from "./components/labelQuestion.vue";
import VipQuestionSelect from "./components/vipQuestionSelect.vue";
import { LabelType } from "@/util/data";
LabelType;
// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

const defaultVipLabel = {
  type: LabelType.VIP,
  name: "",
  ID: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  tenant_id,
};
const store = useStore(Storekey);

const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200];
const offset = ref(0);
const _sortable = ref<"DESC" | "ASC" | null>("DESC");
const _order = ref(["ID"]);
const like = ref("");
const tableData = ref<Studycodemodel.ILabel[]>([]);
const totalCount = ref(0);

onMounted(() => {
  start();
});
async function start() {
  const { rows, count } = await asyncselectlabel({
    type: LabelType.VIP,
    _limit: limit.value,
    _offset: offset.value,
    _sortable: _sortable.value || "DESC",
    _order: _order.value || ["ID"],
    tenant_id,
  });
  tableData.value = rows;
  totalCount.value = count;
}
function handleCurrentChange(val: number) {
  offset.value = limit.value * (val - 1);
  start();
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};
// 排序
function sortchange(row: {
  column: any;
  prop: string;
  order: "ascending" | "descending" | null;
}) {
  const { prop, order } = row;
  if (order === "descending") {
    _sortable.value = "DESC";
  } else if (order === "ascending") {
    _sortable.value = "ASC";
  } else {
    _sortable.value = null; // 没有排序
  }
  _order.value = [prop]; // 每次只排序一个字段
  start();
}
function formatter(updatedAt: string) {
  return toLocaleDateString(updatedAt);
}

// 添加
const fromData = ref<Studycodemodel.ILabel>({ ...defaultVipLabel });
const formRef = ref<FormInstance>();
const dialogVisible = ref(false);
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        await asynccreateorupdatelabel({
          ...fromData.value,
          type: LabelType.VIP,
        });
        ElMessage({ message: "操作成功", type: "success" });
        start();

        dialogVisible.value = false;
        resetFrom();
      } catch (e: any) {
        ElMessage({ message: e, type: "error" });
      }
    } else {
      console.log("error submit!");
    }
  });
};

const update = (row: Studycodemodel.ILabel) => {
  dialogVisible.value = true;
  fromData.value = row;
};
// reset
const resetFrom = () => {
  fromData.value = { ...defaultVipLabel };
};

async function del(ID: number) {
  ElMessageBox.confirm("确定要删除此标签", "警告", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(async () => {
      try {
        await asyncdellabel({ ID });
        ElMessage({ message: "删除成功", type: "success" });
        store.dispatch("actionlabel");
        start();
      } catch (e) {
        ElMessage({ message: String(e), type: "error" });
      }
    })
    .catch(() => {
      ElMessage({ type: "info", message: "已取消" });
    });
}

// 关联题目弹窗
const selectedLabel = ref<Studycodemodel.ILabel>({});
const showVipLabelQuestionDrawer = ref(false);
const addQuestion = (row: Studycodemodel.ILabel) => {
  selectedLabel.value = row;
  showVipLabelQuestionDrawer.value = true;
  console.log(selectedLabel.value);
};

function closeDrawer() {
  showVipLabelQuestionDrawer.value = false;
}

//
const refreshLabelQuestion = ref<() => void>(() => {});
// 传递 `start` 方法给 LabelQuestion
const setRefreshLabelQuestion = (refreshFunc: () => void) => {
  refreshLabelQuestion.value = refreshFunc;
};
// 当 VipQuestionSelect 中添加题目时触发 LabelQuestion 的 start 方法
const onAddQuestion = () => {
  if (refreshLabelQuestion.value) {
    refreshLabelQuestion.value();
  }
};
</script>

<style>
.my-el-drawer {
  min-width: 1000px;
}
</style>

<style>
.vip-label .el-drawer__body {
  padding-bottom: 0;
}
</style>
